import 'package:flutter/material.dart';
import 'package:we_chat/pages/discover/discover_child_page.dart';
import 'package:we_chat/pages/friends/index_bar.dart';
import 'friends_data.dart';
import '../const.dart';

class FriendsPage extends StatefulWidget {
  const FriendsPage({Key? key}) : super(key: key);

  @override
  State<FriendsPage> createState() => _FriendsPageState();
}

class _FriendsPageState extends State<FriendsPage> with AutomaticKeepAliveClientMixin{
  //混入需要重写get方法
  @override
  bool get wantKeepAlive => true;

  //字典里面放item和高度的对应数据
  final Map _goupOffSetMap = {
    INDEX_WORDS[0]:0.0,
    INDEX_WORDS[1]:0.0,
  };


  //用来滑动listView
  ScrollController _scrollController = ScrollController();
  final List<Friends> _listData = [];

  @override
  //首页的 initState 方法得重新run才会运行至此
  void initState() {
    super.initState();

    // _listData..addAll(frisendDatas)..addAll(frisendDatas);
    _listData.addAll(frisendDatas);
    _listData.sort((Friends a, Friends b) {
     return a.indexLetter!.compareTo(b.indexLetter!);
    } );

    var _groupOffSet = 54.5 * 4;
    //经过循环计算，将每一个头的位置算出来，放到字典里
    for(int i=0; i<_listData.length; i++){

      //头部
      if(i<1){
        //第一个加入字典
        _goupOffSetMap.addAll({_listData[i].indexLetter:_groupOffSet});
        _groupOffSet += 84.5;
      } else if(_listData[i].indexLetter == _listData[i-1].indexLetter){
        //没有头，只叠加高度，不加入字典
        _groupOffSet += 54.4;
      } else {
        //下一个头，加入字典
        _goupOffSetMap.addAll({_listData[i].indexLetter:_groupOffSet});
        _groupOffSet += 84.5;
      }
    }
    // print(_goupOffSetMap);

    _scrollController = ScrollController();
  }


  final List<Friends> _headerData = [
    Friends(imageUrl: 'images/新的朋友.png', name: '新的朋友'),
    Friends(imageUrl: 'images/群聊.png', name: '群聊'),
    Friends(imageUrl: 'images/标签.png', name: '标签'),
    Friends(imageUrl: 'images/公众号.png', name: '公众号'),
  ];

  Widget _itemForRow (BuildContext context, int index){
    //系统图标
    if(index < _headerData.length){
      return _FriendCell(name: _headerData[index].name,
        imageAssets: _headerData[index].imageUrl,);
    }else{
      Friends  _data = _listData[index-_headerData.length];
      bool showGroupTitle = true;
      if(index>_headerData.length){
        showGroupTitle = _data.indexLetter != _listData[index-_headerData.length-1].indexLetter;
      }
      return _FriendCell(name: _data.name,
        imageUrl: _data.imageUrl,
        groupTitle: showGroupTitle?_data.indexLetter:null,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: WeChatThemeColor,
        title: Text('通讯录',style: TextStyle(color: Colors.black),),
        actions: [
          GestureDetector(
            onTap: (){
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext builder) => DiscoverChildPage(title: '添加朋友')));
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Image(image: AssetImage('images/icon_friends_add.png'),width: 25,),
            ),
          ),
        ],
      ),
      //Stack多层,Stack经常和Positioned一起布局
      body:GestureDetector(
          onTap: (){
            Navigator.of(context).push(MaterialPageRoute(
                builder: (BuildContext builder) => DiscoverChildPage(title: '聊天')));
          },
        child: Stack(children: [
          Container( color: WeChatThemeColor,
            child:  ListView.builder(
              controller: _scrollController,
              itemCount: _listData.length + _headerData.length,
              itemBuilder: _itemForRow,
            ),),
          IndexBar(
            //设置回调
            indexBarCallBack: (String str){
              if(_goupOffSetMap[str] != null){//不是全部字母都有
                //滚动位置
                _scrollController.animateTo(_goupOffSetMap[str], duration: Duration(microseconds: 1000), curve: Curves.easeIn);
                // print(_goupOffSetMap[str]);
              }
              // print('收到了 $str');
            },
          )
        ],),
      ),
    );
  }
}

class _FriendCell extends StatelessWidget {
  final String? imageUrl;
  final String name;
  final String? groupTitle;
  final String? imageAssets;

  _FriendCell({
    this.imageUrl,
    required this.name,
    this.imageAssets,
    this.groupTitle,

});

  @override
  Widget build(BuildContext context) {
    return Container(
      // color: Colors.white,
      child: Column(children: [
        Container(
          alignment: AlignmentDirectional.centerStart,//左中
          padding: EdgeInsets.only(left: 10),//左边距
          height: groupTitle!=null? 30:0,color: Color.fromRGBO(1, 1, 1, 0.0),
          child: groupTitle!=null?Text('$groupTitle',style: TextStyle(color: Colors.grey,),) :null,),
        Container(
          color: Colors.white,//设置row的白色
          child: Row(
          children: [
            //图片
            Container(

              margin: EdgeInsets.all(10),
              height: 34,
              width: 34,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  //错误示范 -- 在DecorationImage的image里面判断
                  //               image: DecorationImage(
                  //                 image: imageUrl != null
                  //                     ? NetworkImage(imageUrl)
                  //                     : AssetImage(imageAssets),
                  //               ),
                  image: imageUrl != null ?DecorationImage(image:  NetworkImage(imageUrl!),):
                  DecorationImage(image:  AssetImage(imageAssets!),
                  )
              ),

            ),

            //名称
            Container(
              // color: Colors.white,
              child: Text(name),
            )
          ],
        ),),
        //设置分割线
        Container(
          height: 0.5,
          color: WeChatThemeColor,
          child: Row(
            children: [
              Container(height: 0.5,color: Colors.white,width: 50.0,),
              //错误设置分割线
              // Container(height: 0.5,color: WeChatThemeColor,),
            ],
          ),
        ),
      ],)

    );
  }
}

